package org.example.interceptor;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

public class POWInterceptor implements HandlerInterceptor {

    private final String key = "pow:test:";

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       response.setCharacterEncoding("utf8");
        String value = (String)redisTemplate.opsForValue().get(key + 9527);
        if(value != null){
            PrintWriter out = response.getWriter();
            out.write("点击过，未调用完成，不允许继续点击");
            out.flush();
            return false;
        }
        redisTemplate.opsForValue().set(key + 9527, "majian",15, TimeUnit.SECONDS);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        redisTemplate.delete(key+9527);
    }
}
